<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="170"
      size=""
      style="padding-right: 10px; height: 70vh; overflow: auto"
    >
      <el-row
        style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
        >项目基础信息</el-row
      >
      <el-row justify="start" style="margin-top: 10px">
        <el-col :span="8">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="项目编号" prop="prjNum">
            <el-input v-model="formData.prjNum" disabled placeholder="自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目分类" prop="category">
            <el-select v-model="formData.category" placeholder="请选择项目类型" clearable>
              <el-option v-for="item in projectCategorys" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所在城市" prop="areaCode">
            <el-cascader
              v-model="formData.areaCode"
              placeholder="请选择项目归属地区"
              :options="areaoptions"
              @change="handleCascaderChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同竣工日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="是否存在多地施工" prop="isMultiConstruction">
            <el-radio-group v-model="formData.isMultiConstruction">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目位置" prop="address">
            <el-input
              :value="'lat:' + (formData.lat ?? '0') + 'lng:' + (formData.lng ?? '0')"
              placeholder="请选择项目位置"
              @click="bmap1VisibleClick"
            />
            <el-button
              ref="mapBtnRef"
              style="position: absolute; right: -50%; top: 0px"
              type="success"
              plain
              @click="bmap1VisibleClick"
            >
              <i-ep-mapLocation></i-ep-mapLocation>
              选择定位
            </el-button>
            <el-popover
              ref="popoverRef"
              placement="top-end"
              :popper-style="{ padding: '0px' }"
              :width="840"
              :visible="bmap1Visible"
              :virtual-ref="mapBtnRef"
              virtual-triggering
              trigger="click"
              @hide="pupHide"
              @show="pupShow"
            >
              <projectMap
                ref="bmap1Ref"
                :contain-size="{ width: '800px', height: '350px' }"
                :prev-point="projectPoint"
                :contain-id="containId1"
                @map-hide="mapHide"
                @send-project-point="sendProjectPoint"
                @send-project-addr="sendProjectAddr"
              ></projectMap>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传中标通知书/施工合同" prop="atachment">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :span="22">
          <el-form-item label="项目简介" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              style="width: 100%"
              :row="3"
              placeholder="请输入项目简介"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2"> </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { CreateProject, UpdateProject, GetProjectForm } from "@/api/project/projectInfo/index";
import { ProjectCheckInForm } from "@/api/project/projectInfo/types";
import { getDicts } from "@/store/modules/dict";
import { useScreen } from "@/store/modules/screen";
import projectMap from "@/views/manager/common/projectMap/index.vue";
import { bd09togcj02, gcj02towgs84 } from "@/utils/coordtransform";
import { loaderMap } from "@/utils/map";
import { FormRules } from "element-plus/es/components/form/src/types";
import type { UploadUserFile } from "element-plus";

//声明变量
const containId1 = ref(GenNonDuplicateID());
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);
//行政区划
const areaoptions = getDicts("areaTrees").filter((item: { value: number }) => item.value === 540000);
console.log(areaoptions);
//项目行业主管部门
const projectIndustryTypes = getDicts("industryTypes");
//项目分类
const projectCategorys = ref();
// 项目种类
const projectFundsSources = getDicts("projectFundsSource");
//建设性质
const projectPropertys = getDicts("projectPropertys");

//上传文件列表
const fileList = ref<UploadUserFile[]>([]);
const projectPoint = ref({ lat: 29.641156373429688, lng: 91.13585449304729 });
const bmap1Ref = ref();
const bmap1Visible = ref(false);
const isLoaderMap = ref(false);
const mapBtnRef = ref();

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
    }),
  },
});

const { dialogAddOrEdit } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<ProjectCheckInForm>({});
const addOrEditFormRef = ref(ElForm);

//表单验证规则
const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传附件!"));
    return;
  } else {
    callback();
  }
};

const validatorBuildingLength = function (rule: any, value: any, callback: any) {
  if (formData.isMultiConstruction && (formData.buildingLength ?? 0) < 10000) {
    callback(new Error("总长度必须大于10000米"));
    return;
  } else {
    callback();
  }
};
const validatorBuildingArea = function (rule: any, value: any, callback: any) {
  if (formData.isMultiConstruction && (formData.buildingArea ?? 0) < 10000) {
    callback(new Error("总面积必须大于10000平方米"));
    return;
  } else {
    callback();
  }
};
const validatorBuilderLicences = function (rule: any, value: any, callback: any) {
  if (formData.isBuilderLicence && (formData.builderLicences == "" || formData.builderLicences == undefined)) {
    callback(new Error("施工许可证不能为空"));
    return;
  } else {
    callback();
  }
};
const validatorBuilderLicencesGrantDate = function (rule: any, value: any, callback: any) {
  if (formData.isBuilderLicence && formData.builderLicencesGrantDate == undefined) {
    callback(new Error("施工许可证发证日期不能为空"));
    return;
  } else {
    callback();
  }
};
const validatorBuilderLicencesTermDate = function (rule: any, value: any, callback: any) {
  if (formData.isBuilderLicence && formData.builderLicencesTermDate == undefined) {
    callback(new Error("施工许可证有效期不能为空"));
    return;
  } else {
    callback();
  }
};
const rules = reactive<FormRules<ProjectCheckInForm>>({
  name: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
  category: [{ required: true, message: "项目分类不能为空", trigger: "blur" }],
  propertyNum: [{ required: true, message: "建设性质不能为空", trigger: "blur" }],
  industryType: [{ required: true, message: "行业主管部门不能为空", trigger: "blur" }],
  fundsSource: [{ required: true, message: "项目种类不能为空", trigger: "blur" }],
  areaCode: [{ required: true, message: "项目归属地不能为空", trigger: "blur" }],

  isBuilderLicence: [{ required: true, message: "请选择是否有施工许可证", trigger: "blur" }],
  builderLicences: [{ trigger: "blur", validator: validatorBuilderLicences }],
  builderLicencesGrantDate: [{ trigger: "blur", validator: validatorBuilderLicencesGrantDate }],
  builderLicencesTermDate: [{ trigger: "blur", validator: validatorBuilderLicencesTermDate }],
  contractAmount: [{ required: true, message: "中标合同金额不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "请选择监管单位", trigger: "blur" }],
  contractStartDate: [{ required: true, message: "合同开工日期不能为空", trigger: "blur" }],

  endDate: [{ required: true, message: "项目竣工日期不能为空", trigger: "blur" }],
  hasSafeguardingBoard: [{ required: true, message: "请选择是否树立维权告示牌", trigger: "blur" }],
  isMultiConstruction: [{ required: true, message: "请选择是否多地施工", trigger: "blur" }],
  buildingLength: [
    {
      trigger: "blur",
      validator: validatorBuildingLength,
    },
  ],
  buildingArea: [
    {
      trigger: "blur",
      validator: validatorBuildingArea,
    },
  ],
  linkMan: [{ required: true, message: "联系人姓名不能为空", trigger: "blur" }],
  linkPhone: [
    { required: true, message: "联系人电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的电话号码",
      trigger: "blur",
    },
  ],
  atachment: [
    {
      required: true,
      message: "请上传项目文件",
      trigger: "blur",
      validator: validatorAttachment,
    },
  ],
});

function GenNonDuplicateID() {
  let idStr = Date.now().toString(36);
  idStr += Math.random().toString(36).substr(3);
  return idStr;
}

//选择行业分类回调
const changeIndustryType = function (id: any) {
  projectCategorys.value = projectIndustryTypes[id].children;
  formData.category = undefined;
};

//地图加载
if (!BMapGL) {
  loaderMap().then((BMap) => {
    if (BMap) {
      isLoaderMap.value = true;
    }
  });
}

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

/* 地图返回事件监听 */
function sendProjectPoint(currentPoint: { lng: number; lat: number }) {
  let tempgcj = bd09togcj02(currentPoint.lng, currentPoint.lat);
  let tempwgs = gcj02towgs84(tempgcj[0], tempgcj[1]);
  projectPoint.value = currentPoint;
  formData.lat = tempwgs[1];
  formData.lng = tempwgs[0];
}

function sendProjectAddr(addr: string) {
  formData.address = addr;
}

/* 地图隐藏事件 */
function pupHide() {
  if (projectPoint.value) {
  }
  if (bmap1Ref.value) {
    bmap1Ref.value.destroyMap();
  }
}

/* 地图显示事件 */
async function pupShow() {
  if (projectPoint.value) {
    if (bmap1Ref.value && bmap1Ref.value.addMarker && bmap1Ref.value.setCenter && bmap1Visible.value) {
      await bmap1Ref.value.init();
      await bmap1Ref.value.searchAddress();
      bmap1Ref.value.addMarker(projectPoint.value);
      bmap1Ref.value.setCenter(projectPoint.value);
    }
  }
}

function mapHide(choose: boolean) {
  bmap1Visible.value = false;
  if (!choose) {
    formData.lat = undefined;
    formData.lng = undefined;
    formData.address = "";
  }
}
function bmap1VisibleClick() {
  bmap1Visible.value = !bmap1Visible.value;
}

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 1200;
    itemSpan.value = 12;
  }
}
const initForm = async function () {
  if (dialogAddOrEdit.value.id) {
    loading.value = true;
    let res = await GetProjectForm(dialogAddOrEdit.value.id);
    loading.value = false;
    if (res.type === 0) {
      if (res.success) {
        Object.assign(formData, res.data);
        if (res.data.attachmentFiles) {
          let list = Array<any>();
          res.data.attachmentFiles.forEach((item: any) => {
            list.push({
              name: item.friendlyName,
              url: item.objectFilePath,
              status: "success",
              uid: item.id,
            });
          });
          fileList.value = list;
        }
      } else {
      }
    } else {
    }
  }
};

//城市联动赋值
const handleCascaderChange = (value: any) => {
  if (value.length == 3) {
    formData.provinceCode = value[0];
    formData.cityCode = value[1];
    formData.areaCode = value[2];
  }
  // 在这里可以对选中的值进行进一步处理
};
watch(
  () => dialogAddOrEdit.value.visible,
  () => {
    dialogAddOrEdit.value = {};
    if (dialogAddOrEdit.value.visible) {
      initForm();
    }
  }
);
onMounted(async () => {
  initScreen();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.projectId = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (fileList.value.length > 0) {
        formData.attachments = fileList.value.map((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              return item.response.data;
            } else {
              return item.uid;
            }
          }
        });
      }
      if (dialogAddOrEdit.value.id || dialogAddOrEdit.value.id > 0) {
        UpdateProject(formData)
          .then((res) => {
            if (res.type === 0) {
              if (res.success === true) {
                ElMessage.success(res.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(res.msg);
              }
            } else {
              ElMessage.warning(res.msg);
            }
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => (loading.value = false));
      } else {
        CreateProject(formData)
          .then((resp) => {
            if (resp.type === 0) {
              if (resp.success === true) {
                ElMessage.success(resp.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(resp.msg);
              }
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
